package com.hjxy.codetools.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.StringUtil;
import com.hjxy.codetools.interfa.ArtitleServiceInterface;
import com.hjxy.codetools.model.ArtitleModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class RestArtitleController {
    @Autowired
    ArtitleServiceInterface artitleServiceInterface;
    /**
     * 后台调用
     * 查询文章列表 分页
     * 查询条件
     * @param req
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/api/getArtitlesInfo")
    public Map<String, Object> getArtitlesInfo(HttpServletRequest req) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }

        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        int pageIndex =jsonObject.getInteger("pageIndex");
        int pageSize =jsonObject.getInteger("pageSize");
        Map whMap=new HashMap();
        whMap.put("start",(pageIndex - 1) * pageSize);
        whMap.put("end", pageSize);

        if(jsonObject.containsKey("title")) whMap.put("title",jsonObject.getString("title"));
        if(jsonObject.containsKey("typeid"))
            if(!jsonObject.getString("typeid").isEmpty())  whMap.put("code",jsonObject.getString("typeid"));
        List<ArtitleModel> artitleModels = artitleServiceInterface.ArtitlesInfo(whMap);
        int totalNum = artitleServiceInterface.getTotalNum(whMap);
        resultMap.put("data", artitleModels);
        resultMap.put("code", 20000);
        resultMap.put("totalPageNum", totalNum);
        return resultMap;
    }


    /**
     * 后台 调用
     * 根据文章id获取文章信息
     * @param queryItem
     * @return
     * @throws Exception
     */

    @PostMapping(value = "/api/getArtitleByCode")
    public Map<String, Object> getArtitleByCode(@RequestBody Map<String, String> queryItem) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        int id =Integer.parseInt(queryItem.get("code"));
        ArtitleModel artitleModel = artitleServiceInterface.getArtitleById(id);
        resultMap.put("data", artitleModel);
        resultMap.put("code", 20000);
        return resultMap;

    }

    /**
     * 管理后台使用 新增 编辑操作
     *
     * @param req
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/api/updateArtitle")
    public Map<String, Object> updateArtitle(HttpServletRequest req) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }

        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        if (jsonObject.containsKey("id")) {
            //编辑操作
            ArtitleModel artitleModel = new ArtitleModel();
            artitleModel.setId(jsonObject.getInteger("id"));
            artitleModel.setTypeid(jsonObject.getString("typeid"));
            artitleModel.setTitle(jsonObject.getString("title"));
//            artitleModel.setContent(jsonObject.getString("content"));
            String contentStr=jsonObject.getString("content");
            contentStr=contentStr.replace("</pre>","</code></pre>")
                    .replace("<pre class=\"ql-syntax\" spellcheck=\"false\">","<pre class=\"ql-syntax\" spellcheck=\"false\"><code>");
            artitleModel.setContent(contentStr);

            String summarycontentStr=jsonObject.getString("summarycontent");
            if(StringUtil.isNotEmpty(summarycontentStr)){
                summarycontentStr=summarycontentStr.replace("</pre>","</code></pre>")
                        .replace("<pre class=\"ql-syntax\" spellcheck=\"false\">","<pre class=\"ql-syntax\" spellcheck=\"false\"><code>");
                artitleModel.setSummarycontent(summarycontentStr);
            }


            if(jsonObject.containsKey("ishot"))
                artitleModel.setIshot(jsonObject.getBoolean("ishot"));
            artitleModel.setIshot(jsonObject.getBoolean("ishot"));
            artitleModel.setSlturl(jsonObject.getString("slturl"));
            artitleModel.setSummarytxt(jsonObject.getString("summarytxt"));
            artitleModel.setNum(jsonObject.getIntValue("num"));
            int execNum = artitleServiceInterface.updateArtitle(artitleModel);
            if (execNum > 0)
                resultMap.put("code", 20000);
        }
        else {
            //新增功能

            ArtitleModel artitleModel = new ArtitleModel();
            artitleModel.setTypeid(jsonObject.getString("typeid"));
            artitleModel.setTitle(jsonObject.getString("title"));
            String contentStr=jsonObject.getString("content");
            contentStr=contentStr.replace("</pre>","</code></pre>")
                    .replace("<pre class=\"ql-syntax\" spellcheck=\"false\">","<pre class=\"ql-syntax\" spellcheck=\"false\"><code>");
            artitleModel.setContent(contentStr);

            String summarycontentStr=jsonObject.getString("summarycontent");
            if(StringUtil.isNotEmpty(summarycontentStr)){
                summarycontentStr=summarycontentStr.replace("</pre>","</code></pre>")
                        .replace("<pre class=\"ql-syntax\" spellcheck=\"false\">","<pre class=\"ql-syntax\" spellcheck=\"false\"><code>");
                artitleModel.setSummarycontent(summarycontentStr);
            }
//            summarycontentStr=summarycontentStr.replace("</pre>","</code></pre>")
//                    .replace("<pre class=\"ql-syntax\" spellcheck=\"false\">","<pre class=\"ql-syntax\" spellcheck=\"false\"><code>");
//            artitleModel.setSummarycontent(summarycontentStr);


            artitleModel.setSlturl(jsonObject.getString("slturl"));
            if(jsonObject.containsKey("ishot"))
            artitleModel.setIshot(jsonObject.getBoolean("ishot"));
            artitleModel.setSummarytxt(jsonObject.getString("summarytxt"));
            artitleModel.setCreatetime(new Timestamp(System.currentTimeMillis()));
            artitleModel.setRandcode(System.currentTimeMillis()+"");
            artitleModel.setNum(jsonObject.getIntValue("num"));
            int execNum = artitleServiceInterface.insertArtitle(artitleModel);
            if (execNum > 0) {
                resultMap.put("code", 20000);
            } else {
                resultMap.put("code", 50000);
                resultMap.put("msg", "exec failed");
            }

        }
        return resultMap;
    }

    /**
     * 管理后台使用 删除 批量删除 文章
     * @param req
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/api/deleteArtitle")
    public Map<String, Object> deleteArtitle(HttpServletRequest req) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        String rowid = jsonObject.getString("rowid");
        rowid = rowid.endsWith(",") ? rowid.substring(0, rowid.length() - 1) : rowid;
        String[] pcodes = rowid.split(",");
        int[] params = new int[pcodes.length];
        for (int w = 0; w < pcodes.length; w++) {
            params[w] = Integer.parseInt(pcodes[w]);
        }

        int execNum = artitleServiceInterface.deleteArtitle(params);
        if (execNum > 0) {
            resultMap.put("code", 20000);
        }
        return resultMap;
    }
}
